package org.example.chatroom.common.component;

import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

import java.time.LocalDateTime;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: LIUYANJIAO
 * Date: 2025-06-29
 * Time: 21:19
 */
@Component
public class OnlineUserManager {
    //使用线程安全的 哈希表
    //1. 记录用户的WebSocketSession
    private ConcurrentHashMap<Integer, WebSocketSession> sessions = new ConcurrentHashMap<>();
    //2. 记录用户离线的时间
    private ConcurrentHashMap<Integer, LocalDateTime> offlineTime = new ConcurrentHashMap<>();

    //1. 用户上线
    public void online(int userId,WebSocketSession session){
        //判断是否已经在线
        if(sessions.get(userId)!=null){
            //已经在线
            System.out.println(userId +" 已经被登录了 ");
        }
        //之前没有被登录
        sessions.put(userId,session);
        System.out.println(userId+"成功上线");
    }
    //2. 用户下线
    public void offline(int userId,WebSocketSession session){
        WebSocketSession exitSession = sessions.get(userId);
        if(exitSession==session){
            //进行下线操作
            sessions.remove(userId);
            System.out.println(userId+" 下线 ");
            //添加离线时间记录
            offlineTime.put(userId,LocalDateTime.now());
            System.out.println("下线时间为："+offlineTime.get(userId));
        }
    }
    //3. 通过userId获得WebSocketSession
    public  WebSocketSession getsession(int userId){
        return sessions.get(userId);
    }
    //4. 通过userId获得离线时间
    public LocalDateTime getofflineTime(int userId){
        System.out.println("下线时间为："+offlineTime.get(userId));
        return offlineTime.get(userId);
    }
}
